package com.example.pingxue.service;

import com.example.pingxue.entity.Selection;
import com.example.pingxue.entity.Teacher;
import com.example.pingxue.repository.SelectionRepository;
import com.example.pingxue.repository.TeacherRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ScoreService {
    private final SelectionRepository selectionRepository;
    private final TeacherRepository teacherRepository;

    // 行为7：教师给学生打分
    @Transactional
    public void scoreStudent(Long teacherId, Long selectionId, Double midScore,
                             Double finalScore, Double performanceScore) {
        // 1. 加载实体
        Teacher teacher = teacherRepository.getById(teacherId);
        Selection selection = selectionRepository.getById(selectionId);

        // 2. 权限校验（数据安全）
        boolean hasPermission = teacher.getClazz().stream()
                .anyMatch(clazz -> clazz.getId().equals(selection.getClazz().getId()));
        if (!hasPermission) {
            throw new SecurityException("无权为该班级学生打分");
        }

        // 3. 设置成绩
        selection.setMidScore(midScore);
        selection.setFinalScore(finalScore);
        selection.setPerformanceScore(performanceScore);

        selectionRepository.save(selection);
    }
}
